const tableEle = document.querySelector('table')    //商品列表
const totalPriceEle = document.querySelector('.total-price') //总价
const btnNumEle = document.querySelector('.bot_num') //计算总的价格
const endEle = document.querySelector('.end')  //结算按钮


let ArrayStr = localStorage.getItem('PANDACART') //从locaStorage获取数据
let cartArray = JSON.parse(ArrayStr) || []
let stateAll = false //全选按钮选中

/***------------------------------- 商品列表渲染------------------------------- */
function showProductList() {
    //初始化商品列表 表头
    let str = `
                <tr>
                    <th class="id">序号</th>
                    <th><input type="checkbox" class="checkbox-all" ${stateAll ? 'checked' : ''}></th>
                    <th>图片</th>
                    <th class = "message">商品信息</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>总价</th>
                    <th>操作</th>
                </tr>
         `
    //遍历商品列表生成商品列表

    let productArry = cartArray.map(item => {
        return `
            <tr>
                <td class="id">${item.id}</td>
                <td><input type = "checkbox" class="checkbox-item" ${item.state ? 'checked' : ''}></td>
                
                <td><img src = "${item.img}" width="80px"></td>
                <td><div class = "mess">${item.title}</div></td>
                <td>￥${item.price}</td>
                <td><input type="button" name="minus" value="-" ${item.num <= 0 ? 'disabled' : ''}><input type="text" value="${item.num}" name="amount"><input type="button" name="add" value="+">
                </td>
                 <td class="sumPrice" width="100px">￥${item.sumPrice}</td>
                <td>
                    <a href="#">移入收藏</a><br>
                    <a href="#" class="delete-btn">删除</a>
                </td>
            </tr>
        `
    })
    str = str + productArry.join('')
    tableEle.innerHTML = str
}

/*------------------------------------委托事件-----------------------------*/
function addTarget() {
    let iptEle = document.querySelector('input[name="amount"]')
    // 委托给table
    tableEle.addEventListener('click', e => {
        e = e || window.event
        let target = e.target || e.srcElement
        /*---加号---点击加号数+1，总价--商品总价改变 */
        if (target.getAttribute('name') == 'add') {
            //1.通过操作DOM节点，获取当前id的值
            let id = target.parentNode.parentNode.firstElementChild.innerHTML
            console.log(id);
            // 2.遍历返回第一个满足条件的数组对象
            let newArray = cartArray.find(item => item.id == id)
            newArray.num++
            newArray.sumPrice = (newArray.price * newArray.num).toFixed(2)
            sumPrice()
            showProductList()
        }

        //---减操作---
        if (target.getAttribute('name') == 'minus') {
            //1.通过操作DOM节点，获取当前id的值
            let id = target.parentNode.parentNode.firstElementChild.innerHTML
            // 2.遍历返回第一个满足条件的数组对象
            let newArray = cartArray.find(item => item.id == id)
            newArray.num--
            newArray.sumPrice = (newArray.price * newArray.num).toFixed(2)
            sumPrice()
            showProductList()
        }

        //---删除操作---
        if (target.getAttribute('class') == 'delete-btn') {
            if (confirm('是否确认删除')) {
                //1.通过操作DOM节点，获取当前id的值
                let id = target.parentNode.parentNode.firstElementChild.innerHTML
                // 2.遍历返回第一个满足条件的数组对象下标
                let index = cartArray.findIndex((item, index) => item.id == id)
                //3.通过数组截取删除当前点击的数组对象
                cartArray.splice(index, 1)
                localStorage.setItem('PANDACART', JSON.stringify(cartArray))
                sumPrice()
                showProductList()
            }
        }

        //---全选操作---
        if (target.getAttribute('class') == 'checkbox-all') {
            stateAll = !stateAll
            //遍历数组里的复选框的选中状态随全选框状态改变而改变
            cartArray.forEach(item => item.state = stateAll)
            /**选中全选，显示全部商品数量***以及计算总价****结算按钮的样式*/
            if (stateAll) {
                let numSum = cartArray.reduce((s, item) => s + item.num, 0)
                let priceSum = cartArray.reduce((s, item) => s + item.sumPrice, 0)
                endEle.style.backgroundColor = 'red'
                btnNumEle.innerHTML = numSum.toFixed(2)
                totalPriceEle.innerHTML = priceSum.toFixed(2)
            } else {
                btnNumEle.innerHTML = '0'
                totalPriceEle.innerHTML = '0'
                endEle.style.backgroundColor = ''
            }
            showProductList()
        }
        //---复选框操作---
        if (target.getAttribute('class') == 'checkbox-item') {
            //改变自身状态的值
            let id = target.parentNode.previousElementSibling.innerHTML
            let newArray = cartArray.find(item => item.id == id)
            newArray.state = !newArray.state
            /**选中复选框，显示选中全部商品数量  *以及计算总价*****结算按钮的样式*/
            let numList = cartArray.filter(item => item.state == true)
            let numS = numList.reduce((s, item) => s + item.num, 0)
            let priceS = numList.reduce((s, item) => s + item.sumPrice * item.num, 0)
            btnNumEle.innerHTML = numS.toFixed(2)
            totalPriceEle.innerHTML = priceS.toFixed(2)
            if (newArray.state) {
                endEle.style.backgroundColor = 'red'
            } else {
                endEle.style.backgroundColor = ''
            }

            stateAll = cartArray.every(item => item.state == true)

            showProductList()
        }

    })

    //改变输入框的值
    tableEle.addEventListener('change', e => {
        e = e || window.event
        let target = e.target || e.srcElement
        if (target.getAttribute('name') == 'amount') {
            //获取输入框的值
            let num = target.value
            let id = target.parentNode.parentNode.firstElementChild.innerHTML
            // 找到当前所在的数组项
            let newbookList = cartArray.find(item => item.id == id)
            // 商品数量
            newbookList.number = num
            // 找到单价---计算总价
            newbookList.sumPrice = (newbookList.price * num).toFixed(2)
            endEle.style.backgroundColor = 'red'
        }
        //计算总价
        sumPrice()
    })
    //重新加载数据
    showProductList()
}

/*----------------------------------计算商品总价----------------------------*/
function sumPrice() {
    let totalPrice = 0
    totalPrice = cartArray.reduce((s, item) => {
        return s += Number(item.sumPrice)
    }, 0)
    totalPriceEle.innerHTML = totalPrice.toFixed(2)
}

showProductList()
addTarget()